package game.unitmanager 
{
	import game.Game;
	import game.map.Army;
	import game.map.Map;
	import game.map.Province;
	import game.map.Unit;
	import game.mapviewer.MapViewer;
	/**
	 * ...
	 * @author rnk
	 */
	public class UnitsManager 
	{
		private var armies:Array = [];
		public var papa:Game;
		
		public function UnitsManager() 
		{
			
		}
		
		public function AddUnit(provinceUid:String,unitType:String,loyalty:int=0):ArmyController
		{
			var mapModel:Map = papa.mapModel;
			var mapView:MapViewer = papa.mapView;
			
			//get army in province
			var armyController:ArmyController = GetArmy(provinceUid);
			
			//if there is no army create one
			if (!armyController) 
			{
				
				var provinceModel:Province = mapModel.GetProvince(provinceUid);
				var armyModel:Army = provinceModel.army;
				var unitModel:Unit = new Unit(unitType);	
				
				provinceModel.AddUnit(unitModel);
				
				armyController = new ArmyController();
				armyController.papa = this;
				armyController.model = armyModel = provinceModel.army;
				armyController.view = mapView.AddArmy(provinceUid, armyModel, armyController);
				
				armies.push(armyController);
				
			} else
			//if there is just add unit
			{
				armyController.AddUnit(unitType);
			}
			
			if (armyController.loyalty != loyalty)
			{
				armyController.loyalty = loyalty;
				armyController.view.Refresh();
			}
			
			
			return armyController;
			
		}
		
		public function GetArmy(provinceUid:String):ArmyController
		{
			for each (var army:ArmyController in armies) 
			{
				if (army.model && army.model.province && army.model.province.uid == provinceUid)
					return army;
			}
			return null;
		}
		
		public function RemoveArmy(army:ArmyController):void
		{
			var idx:int = armies.indexOf(army);
			if (idx >= 0) armies.splice(idx, 1);
			army.papa = null;
			army.view = null;
			army.model = null;
		}
		
		public function GetArmies():Array
		{
			return armies.slice();
		}
		
		public function GetArmiesSupportingThisProvince(provinceUid:String):Array
		{
			var result:Array = [];
			
			for each (var army:ArmyController in armies) 
			{
				if (army.supportProvince == provinceUid)
					result.push(army);
			}
			
			return result;
		}
		
		
	}

}